package com.proposition.support.controller;

import com.proposition.commons.model.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @author 杨凯
 */
@Controller
public class LoginController {

	private static final Logger log = LoggerFactory.getLogger(LoginController.class);

	@RequestMapping("/login")
	public String login() {
		return "login";
	}

	@RequestMapping("/loginUser")
	public String loginUser(String username, String password, boolean rememberMe, HttpServletRequest request, Model model) {
		try {
			model.addAttribute("username", username);
			UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, password);
			usernamePasswordToken.setRememberMe(rememberMe);
			Subject subject = SecurityUtils.getSubject();
			//完成登录
			subject.login(usernamePasswordToken);
			return "redirect:/";
		} catch (Exception e) {
			String ex = e.getClass().getName();
			if (ex != null) {
				if (UnknownAccountException.class.getName().equals(ex)) {
					log.info("用户名不存在");
					model.addAttribute("status", "1001");
				} else if (IncorrectCredentialsException.class.getName().equals(ex)) {
					model.addAttribute("status", "1002");
					log.info("账户或密码错误！");
				} else {
					model.addAttribute("status", "1003");
					log.error("未知错误");
				}
			}
			//返回登录页面
			return "login";
		}
	}

	@RequestMapping("/logOut")
	public String logOut(HttpSession session) {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "redirect:/login";
	}

}
